package com.bocai.grainshop.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bocai.common.constant.ProductConstant;
import com.bocai.common.to.SkuReductionTo;
import com.bocai.common.to.SpuBoundsTo;
import com.bocai.common.to.es.SkuEsModel;
import com.bocai.common.utils.R;
import com.bocai.grainshop.product.dao.SpuInfoDescDao;
import com.bocai.grainshop.product.entity.*;
import com.bocai.grainshop.product.feign.CouponFeignService;
import com.bocai.grainshop.product.feign.SreachFeignService;
import com.bocai.grainshop.product.feign.WareFeignService;
import com.bocai.grainshop.product.service.*;
import com.bocai.grainshop.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bocai.common.utils.PageUtils;
import com.bocai.common.utils.Query;

import com.bocai.grainshop.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Resource
    private SpuInfoDescDao spuInfoDescDao;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SreachFeignService sreachFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * @Author: SunJinbo
     * @Description  发布商品保存
     * @Param [spuVo]
     * @return void      
     * @Data Created in 2022/3/26 16:44
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuVo) {
        //1.保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuVo,spuInfoEntity);
        spuInfoEntity.setUpdateTime(new Date());
        spuInfoEntity.setCreateTime(new Date());
        this.BaseSaveSpuInfo(spuInfoEntity);

        //2.保存spu的描述图片 pms_spu_info_desc
        List<String> decript = spuVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",",decript));
        this.BaseSaveSpuInfoDesc(spuInfoDescEntity);

        //3.保存spu的图片集 pms_spu_images
        List<String> images = spuVo.getImages();
        spuImagesService.savaImages(spuInfoEntity.getId(),images);

        //4.保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuVo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(attr.getAttrId());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            AttrEntity byId = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrName(byId.getAttrName());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.savaBaseAttr(collect);

        //5.保存spu的积分信息 gulimall_sms -> sms_spu_bounds
        Bounds bounds = spuVo.getBounds();
        //远程传参  to  common包中
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds,spuBoundsTo);
        spuBoundsTo.setSpuId(spuInfoEntity.getId());
        couponFeignService.savaBounds(spuBoundsTo);

        //6.保存sku的基本信息 pms_sku_info
        List<Skus> skus = spuVo.getSkus();
        if(skus!=null && skus.size()>0){

            skus.forEach(sku -> {

                //找到默认图片
                String DefaultImage = "";
                for (Images i : sku.getImages()){
                    if(i.getDefaultImg() == 1){
                        DefaultImage = i.getImgUrl();
                    }
                }

                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(DefaultImage);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                //保存后 主键自动赋值
                //7.保存sku的图片信息 pms_sku_images
                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> imageCollect = sku.getImages().stream().map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(image.getImgUrl());
                    skuImagesEntity.setDefaultImg(image.getDefaultImg());
                    return skuImagesEntity;
                }).filter(pojo->{
                    //返回true就是需要  false就是过滤掉
                    return StringUtils.hasText(pojo.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(imageCollect);

                //8.保存sku的销售属性信息 pms_sku_sale_attr_value
                List<Attr> attr = sku.getAttr();
                List<SkuSaleAttrValueEntity> valueEntityList = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(valueEntityList);

                //9.保存sku的优惠和满减等信息 gulimall_sms -> sms_sku_lodder sms_sku_full_reduction
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku,skuReductionTo);
                //报500错误  是因为copy时list<MemberPrice> 字段相同 包不同 无法copy
                skuReductionTo.setSkuId(skuId);
                if(skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1 || skuReductionTo.getFullCount()>0){
                    couponFeignService.savaInfo(skuReductionTo);
                }
            });
        }
    }

    @Override
    public void BaseSaveSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public void BaseSaveSpuInfoDesc(SpuInfoDescEntity spuInfoDescEntity) {
        spuInfoDescDao.insert(spuInfoDescEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if(StringUtils.hasText(key)){
            //有or的用括号括起来  and()
            wrapper.and((w)->{
                w.eq("id",key).or().like("spu_name",key);
            });
        }

        String status = (String) params.get("status");
        if(StringUtils.hasText(status)){
            wrapper.eq("publish_status",status);
        }

        String brandId = (String) params.get("brandId");
        if(StringUtils.hasText(brandId) && !"0".equals(brandId)){
            wrapper.eq("brand_id",brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if(StringUtils.hasText(catelogId) && !"0".equals(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        //查出该spuId下的信息
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSpusBySpuId(spuId);
        //获取skuId集合
        List<Long> longList = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //查询spu所有可以被检索的规格属性
        List<ProductAttrValueEntity> valueEntities = productAttrValueService.baseAttrlistforspu(spuId);
        //收集该spuId下的所有attrId
        List<Long> list = valueEntities.stream().map(obj -> {
            return obj.getAttrId();
        }).collect(Collectors.toList());
        //找出可以被检索的attrId集合
        List<Long> attrIds = attrService.selectAttrByAttrId(list);

        Set<Long> setId = new HashSet<>(attrIds);

        List<SkuEsModel.Attrs> attrsList = valueEntities.stream().filter(obj -> {
            return setId.contains(obj.getAttrId());
        }).map(obj -> {
            SkuEsModel.Attrs attr = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(obj, attr);
            return attr;
        }).collect(Collectors.toList());

        Map<Long, Boolean> booleanMap = null;
        try {
            //远程调用查询库存系统是否有库存
            R hasStock = wareFeignService.getSkuHasStock(longList);
            //推荐R带泛  默认为map
            Object vos = hasStock.get("vos");
            String s = JSON.toJSONString(vos);
            List<SkuHasStockVo> skuHasStockVos = JSON.parseObject(s, new TypeReference<List<SkuHasStockVo>>() {
            });
            //toMap 第一个参数是key  第二个是值
            booleanMap = skuHasStockVos.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
        } catch (Exception e) {
            log.error("库存服务查询异常",e);
            e.printStackTrace();
        }
        //封装每个spu的信息
        Map<Long, Boolean> finalBooleanMap = booleanMap;

        List<SkuEsModel> collect = skuInfoEntities.stream().map(obj -> {
            //过度对象
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(obj, skuEsModel);
            skuEsModel.setSkuImg(obj.getSkuDefaultImg());
            skuEsModel.setSkuPrice(obj.getPrice());
            //热度评分
            if(finalBooleanMap == null){
                skuEsModel.setHasStock(true);
            }else {
                skuEsModel.setHasStock(finalBooleanMap.get(obj.getSkuId()));
            }
            skuEsModel.setHotScore(0L);
            //查询品牌和分类的名字信息
            BrandEntity byId = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(byId.getName());
            skuEsModel.setBrandImg(byId.getLogo());
            CategoryEntity id = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(id.getName());

            skuEsModel.setAttrs(attrsList);
            return skuEsModel;
        }).collect(Collectors.toList());
        //发送es进行保存
        R r = sreachFeignService.productStatusUp(collect);
        Object o = r.get("boolean");
        Boolean aBoolean = false;
        if(o!=null){
            String s = JSON.toJSONString(o);
            aBoolean = JSON.parseObject(s, new TypeReference<Boolean>() {
            });
        }
        if(aBoolean == true){
            //调用成功！ 修改spu_info 的最新状态
            this.baseMapper.updateSpuStatus(spuId, ProductConstant.ProductStatusEnum.SPU_UP.getCode());
        }else {
            //调用失败
            //TODO 接口幂等性  重复调用 重试机制
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySpuId(Long skuId) {
        SkuInfoEntity byId = skuInfoService.getById(skuId);
        return this.getById(byId.getSpuId());
    }

}